import Cookies from 'js-cookie'
import { defineStore } from 'pinia'
import type { Store } from './types'
import { ElMessageBox, ElMessage } from 'element-plus'
import APIAuth from "~/api/auth"
import type { LoginResult } from '~/api/auth/types'
import { useSocket } from '~/stores/socket/index'

export const useAuth = defineStore('auth', {
    state: (): Store => ({
        /** 是否为登录状态 */
        token: '',
        info: {},
        dialogLoginAndRegisterVisible: false,
        getNotifySums: {},
        getNotify: []
    }),
    actions: {
        setInfo(info: LoginResult): void {
            const config = useRuntimeConfig()
            this.token = info.sessionKey || ''
            localStorage.setItem('info', JSON.stringify(info))
            Cookies.set('token', this.token, { domain: config.public.NUXT_APP_COOKIE_URL, expires: 27 })
            this.setPersonalInfo()
        },
        async setPersonalInfo() {
            if (this.token) {
                const { initSocket } = useSocket()
                const { data } = await APIAuth.getAllUser()
                this.info = data.getPersonal
                this.getNotifySums = data.getNotifySums
                this.getNotify = data.getNotify
                initSocket()
            }
        },
        clearInfo(): void {
            const config = useRuntimeConfig()
            this.token = ''
            localStorage.removeItem('info')
            this.info = {}
            Cookies.remove('token', { domain: config.public.NUXT_APP_COOKIE_URL })
        },
        /** 判断是否登录，可以进行下一步操作 */
        isNextOperation(): void | boolean {
            if (this.token) return true
            ElMessageBox.confirm(
                '未登录，是否前往登录？',
                '提示',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                this.dialogLoginAndRegisterVisible = true
            }).catch(() => {
                ElMessage.info('已取消')
            })
        }
    }
})
